﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BezierEffectScript : EffectScript
{
    public BezierDirection bezierDirection = BezierDirection.RANDOM;
    public float offsetMin = 2.5f;
    public float offsetMax = 5f;
    Vector3 topOfBeizer;
    private void OnDisable()
    {
        bezierDirection = BezierDirection.RANDOM;
        offsetMin = 2.5f;
        offsetMax = 5f;
    }
    public BezierEffectScript SetOffset(float min, float max)
    {
        offsetMin = min;
        offsetMax = max;
        return this;
    }
    public BezierEffectScript SetTopOfBezier(Vector3 top)
    {
        bezierDirection = BezierDirection.CUSTOM;
        topOfBeizer = top;
        return this;
    }
    public override void Init()
    {
        base.Init();
        if (bezierDirection == BezierDirection.RANDOM)
        {
            bezierDirection = (BezierDirection)Random.Range(1, 5);
        }
        switch (bezierDirection)
        {
            case BezierDirection.UP:
                topOfBeizer = Vector3.up * Random.Range(offsetMin, offsetMax);
                break;
            case BezierDirection.DOWN:
                topOfBeizer = Vector3.down * Random.Range(offsetMin, offsetMax);
                break;
            case BezierDirection.LEFT:
                topOfBeizer = Vector3.left * Random.Range(offsetMin, offsetMax);
                break;
            case BezierDirection.RIGHT:
                topOfBeizer = Vector3.right * Random.Range(offsetMin, offsetMax);
                break;
            case BezierDirection.CUSTOM:
                break;
            default:
                topOfBeizer = Vector3.up;
                break;
        }
    }
    public override void UpdatePosition(float delta)
    {
        if(space == Space.World)
        {
            transform.position = CalculateCubicBezierPoint(delta, fromData.position, fromData.position + topOfBeizer, toData.position);
        }
        else
        {
            transform.localPosition = CalculateCubicBezierPoint(delta, fromData.position, fromData.position + topOfBeizer, toData.position);
        }
    }

    Vector3 CalculateCubicBezierPoint(float t, Vector3 p0, Vector3 p1, Vector3 p2)
    {
        float u = 1 - t;
        float tt = t * t;
        float uu = u * u;
        Vector3 p = uu * p0;
        p += 2 * u * t * p1;
        p += tt * p2;

        if (Vector3.Magnitude(p - p2) > 0.05f && t >= 0.99f)
            p = p2;
        return p;
    }
}

[System.Serializable]
public enum BezierDirection
{
    RANDOM = 0,
    UP = 1,
    DOWN = 2,
    LEFT = 3,
    RIGHT = 4,
    CUSTOM = 5
}
